import express = require('express');
import path = require('path');
import favicon = require('serve-favicon');
import logger = require('morgan');
import mongo = require('connect-mongo');
import session = require('express-session');
import { index } from './routes/index';
import { user } from './routes/users';
import { remote } from './routes/remote';
import { service } from './config/services.dev';
import http = require('http');
import { config } from './config/app.dev';
import { ENGINE_METHOD_CIPHERS } from 'constants';
let MongoStore = mongo(session);

export let app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));

// Session 中间件
app.use(session({
  name: config.name,
  secret: config.secret,
  cookie: {
    maxAge: config.maxAge
  },
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({
    url: config.url
  })
}));

app.use(express.static(path.join(__dirname, 'public')));


app.use('/', index);
app.use('/users', user);
app.use('/api', remote);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 注册测试服务
app.locals['services'] = {};
app.locals['services'][service.id] = service;

http.createServer(app).listen(3000, function () {
  console.log(`监听端口：3000`);
});